<template>
  <div class="login-container">
    <div class="login-form">
      <div class="login-header">
        <h2 class="title">
          <el-icon class="title-icon"><Reading /></el-icon>
          登录学生信息管理系统
        </h2>
        <p class="subtitle">现代化教育管理平台</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form-content"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            :suffix-icon="showPassword ? View : Hide"
            show-password
            @click="togglePasswordVisibility"
          />
        </el-form-item>
        
        
        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe" size="large">
            记住我
          </el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <div class="login-buttons">
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              @click="handleLogin"
              class="login-btn"
            >
              <el-icon><Right /></el-icon>
              登录
            </el-button>
            <el-button
              type="warning"
              size="large"
              @click="showChangePasswordDialog"
              class="change-password-btn"
            >
              <el-icon><Key /></el-icon>
              修改密码
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="changePasswordDialogVisible"
      title="修改密码"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="changePasswordFormRef"
        :model="changePasswordForm"
        :rules="changePasswordRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="changePasswordForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="changePasswordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="changePasswordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="changePasswordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelChangePassword">取消</el-button>
          <el-button
            type="primary"
            :loading="changePasswordLoading"
            @click="handleChangePassword"
          >
            确认修改
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 背景装饰 -->
    <div class="login-bg">
      <div class="bg-circle circle-1"></div>
      <div class="bg-circle circle-2"></div>
      <div class="bg-circle circle-3"></div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { User, Lock, View, Hide, Right, Key, Reading } from '@element-plus/icons-vue'
import { changePassword } from '@/api/user'

export default {
  name: 'Login',
  components: {
    User,
    Lock,
    View,
    Hide,
    Right,
    Key,
    Reading
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    
    const loginFormRef = ref()
    const loading = ref(false)
    const showPassword = ref(false)
    const redirectTimer = ref(null)
    
    // 修改密码相关状态
    const changePasswordDialogVisible = ref(false)
    const changePasswordFormRef = ref()
    const changePasswordLoading = ref(false)
    
    // 登录表单数据
    const loginForm = reactive({
      username: '',
      password: '',
      rememberMe: false
    })
    
    // 修改密码表单数据
    const changePasswordForm = reactive({
      username: '',
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 表单验证规则
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    }
    
    // 修改密码验证规则
    const changePasswordRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== changePasswordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    
    
    // 登录处理
    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      try {
        const valid = await loginFormRef.value.validate()
        if (!valid) return
        
        loading.value = true
        
        // 调用登录API
        console.log('准备调用store.dispatch user/login')
        console.log('登录表单数据:', loginForm)
        
        const response = await store.dispatch('user/login', loginForm)
        
        console.log('登录响应:', response)
        console.log('当前token (getter):', store.getters['user/token'])
        console.log('当前用户信息 (getter):', store.getters['user/userInfo'])
        console.log('当前token (state):', store.state.user.token)
        console.log('当前用户信息 (state):', store.state.user.userInfo)
        
        // 显示成功消息
        const successMessage = response.data?.message || response.message || '登录成功！'
        ElMessage.success(successMessage)
        
        // 等待Vue响应式更新完成
        console.log('等待Vue响应式更新完成...')
        await nextTick()
        
        // 再次检查token状态
        console.log('跳转前检查state token:', store.state.user.token)
        
        // 立即跳转，避免组件卸载问题
        console.log('准备跳转到dashboard')
        try {
          await router.push('/dashboard')
          console.log('跳转成功')
        } catch (err) {
          console.error('跳转失败:', err)
        }
        
      } catch (error) {
        console.error('登录失败:', error)
        console.error('错误详情:', error.response || error.message || error)
        ElMessage.error(error.message || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
    
    // 显示修改密码弹窗
    const showChangePasswordDialog = () => {
      changePasswordDialogVisible.value = true
      // 重置表单
      Object.assign(changePasswordForm, {
        username: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
    }
    
    // 取消修改密码
    const cancelChangePassword = () => {
      changePasswordDialogVisible.value = false
      if (changePasswordFormRef.value) {
        changePasswordFormRef.value.resetFields()
      }
    }
    
    // 处理修改密码
    const handleChangePassword = async () => {
      if (!changePasswordFormRef.value) return
      
      try {
        const valid = await changePasswordFormRef.value.validate()
        if (!valid) return
        
        changePasswordLoading.value = true
        
        // 调用API修改密码
        const passwordData = {
          username: changePasswordForm.username,
          oldPassword: changePasswordForm.oldPassword,
          newPassword: changePasswordForm.newPassword
        }
        
        const response = await changePassword(passwordData)
        
        // 检查响应是否成功
        if (response && (response.code === 200 || response.code === 0)) {
          ElMessage.success('密码修改成功')
          // 关闭弹窗并重置表单
          changePasswordDialogVisible.value = false
          changePasswordFormRef.value.resetFields()
        } else {
          ElMessage.error(response?.message || '密码修改失败')
        }
        
      } catch (error) {
        console.error('修改密码失败:', error)
        // 错误信息已经在响应拦截器中处理了
      } finally {
        changePasswordLoading.value = false
      }
    }
    
    
    // 切换密码可见性
    const togglePasswordVisibility = () => {
      showPassword.value = !showPassword.value
    }
    
    // 页面加载完成
    onMounted(() => {
      // 检查是否已登录
      if (store.getters['user/isLoggedIn']) {
        router.push('/dashboard')
      }
    })
    
    // 组件卸载时清理定时器
    onUnmounted(() => {
      if (redirectTimer.value) {
        clearTimeout(redirectTimer.value)
        redirectTimer.value = null
      }
    })
    
    return {
      loginFormRef,
      loading,
      showPassword,
      loginForm,
      loginRules,
      handleLogin,
      togglePasswordVisibility,
      // 修改密码相关
      changePasswordDialogVisible,
      changePasswordFormRef,
      changePasswordLoading,
      changePasswordForm,
      changePasswordRules,
      showChangePasswordDialog,
      cancelChangePassword,
      handleChangePassword
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.login-form {
  position: relative;
  z-index: 10;
  width: 100%;
  max-width: 450px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
  
  .title {
    font-size: 28px;
    font-weight: 600;
    color: #2c3e50;
    margin: 0 0 10px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    
    .title-icon {
      font-size: 32px;
      color: #409eff;
    }
  }
  
  .subtitle {
    font-size: 14px;
    color: #909399;
    margin: 0;
  }
}

.login-form-content {
  .el-form-item {
    margin-bottom: 24px;
    
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      border: 1px solid #e4e7ed;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: #409eff;
      }
      
      &.is-focus {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
    
    :deep(.el-select) {
      .el-input__wrapper {
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.login-buttons {
  display: flex;
  gap: 16px;
  width: 100%;
  
  .login-btn,
  .change-password-btn {
    flex: 1;
    height: 48px;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }
  }
  
  .login-btn {
    background: linear-gradient(135deg, #409eff, #66b3ff);
    border: none;
    
    &:hover {
      background: linear-gradient(135deg, #66b3ff, #409eff);
    }
  }
  
  .change-password-btn {
    background: linear-gradient(135deg, #e6a23c, #f0c78a);
    border: none;
    
    &:hover {
      background: linear-gradient(135deg, #f0c78a, #e6a23c);
    }
  }
}


.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
  
  .bg-circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    animation: float 6s ease-in-out infinite;
    
    &.circle-1 {
      width: 200px;
      height: 200px;
      top: 10%;
      left: 10%;
      animation-delay: 0s;
    }
    
    &.circle-2 {
      width: 150px;
      height: 150px;
      top: 60%;
      right: 10%;
      animation-delay: 2s;
    }
    
    &.circle-3 {
      width: 100px;
      height: 100px;
      bottom: 20%;
      left: 20%;
      animation-delay: 4s;
    }
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-form {
    margin: 20px;
    padding: 30px 20px;
    max-width: none;
  }
  
  .login-header .title {
    font-size: 24px;
  }
  
  .login-buttons {
    flex-direction: column;
    
    .login-btn,
    .change-password-btn {
      width: 100%;
    }
  }
}
</style>
